<template>
  <div class="recipe-detail-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
        title=""
        left-arrow
        @click-left="onClickLeft"
        class="transparent-nav"
    />

    <!-- 菜品主图 -->
    <div class="recipe-main-image">
      <img
          src="https://tse2-mm.cn.bing.net/th/id/OIP-C.DJQiixSmCzZUGZbRyjlBoAHaE6?w=218&h=180&c=7&r=0&o=7&dpr=1.3&pid=1.7&rm=3"
          :alt="recipe.title || '菜品图片'"
          class="main-img"
      >
    </div>

    <!-- 菜品标题和作者信息 -->
    <div class="recipe-header">
      <h1 class="recipe-title">{{ recipe.title }}</h1>

      <div class="author-info">
        <img
            :src="recipe.user?.avatar || 'https://picsum.photos/60/60?random=10'"
            alt="作者头像"
            class="author-avatar"
        >
        <div class="author-details">
          <div class="author-name">
            {{ recipe.user?.username }}
            <van-icon name="star" color="#FFB800" size="14" v-if="recipe.user?.isVip" />
          </div>
          <div class="publish-time">{{ formatTime(recipe.createTime) }}</div>
        </div>
      </div>
    </div>

    <!-- 菜品内容 -->
    <div class="recipe-content">
      <div v-html="recipe.content" class="content-text"></div>
    </div>

    <!-- 评论区 -->
    <div class="comments-section">
      <h2 class="section-title">评论区 ({{ totalCommentCount }})</h2>

      <!-- 评论输入框 -->
      <div class="comment-input" v-if="admin">
        <img
            :src="admin.avatar || 'https://picsum.photos/40/40?random=20'"
            alt="当前用户头像"
            class="comment-avatar"
        >
        <van-field
            v-model="commentText"
            placeholder="写下你的评论..."
            class="comment-field"
            :border="false"
            @keyup.enter="submitComment"
        />
        <van-button
            class="submit-btn"
            size="small"
            round
            type="primary"
            @click="submitComment"
        >
          发布
        </van-button>
      </div>

      <!-- 评论列表 -->
      <div class="comments-list">
        <div class="comment-item" v-for="(comment, index) in comments" :key="comment.id">
          <img
              :src="comment.avatar || 'https://picsum.photos/40/40?random=' + comment.id"
              alt="评论者头像"
              class="comment-avatar"
          >
          <div class="comment-content">
            <div class="comment-header">
              <span class="comment-author">
                {{ comment.username }}
                <van-icon name="vip-card" color="#FFB800" size="12" v-if="comment.isVip" />
              </span>
              <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
            </div>
            <p class="comment-text">{{ comment.content }}</p>

            <div class="comment-actions">
              <div class="action-item" @click="likeComment(comment)">
                <van-icon
                    :name="comment.liked ? 'like' : 'like-o'"
                    size="16"
                    :color="comment.liked ? '#FF6B6B' : '#999'"
                />
                <span class="action-count">{{ comment.likeCount || 0 }}</span>
              </div>
              <div class="action-item" @click="replyToComment(comment)">
                <van-icon name="reply" size="16" color="#999" />
                <span>回复</span>
              </div>
            </div>

            <!-- 评论的回复 -->
            <div class="comment-replies" v-if="comment.replyComments && comment.replyComments.length">
              <div class="reply-item" v-for="reply in comment.replyComments" :key="reply.id">
                <img
                    :src="reply.avatar || 'https://picsum.photos/40/40?random=' + reply.id"
                    alt="回复者头像"
                    class="reply-avatar"
                />
                <div class="reply-content">
                  <div class="reply-header">
                    <span class="reply-author">
                      {{ reply.username }}
                      <van-icon name="vip-card" color="#FFB800" size="12" v-if="reply.isVip" />
                    </span>
                    <span class="reply-time">{{ formatTime(reply.createTime) }}</span>
                  </div>
                  <p class="reply-text">
                    <span v-if="reply.parentUsername" style="color: #FF6B6B;">回复 @{{ reply.parentUsername }}：</span>
                    {{ reply.content }}
                  </p>

                  <div class="reply-actions">
                    <div class="action-item" @click="likeComment(reply)">
                      <van-icon
                          :name="reply.liked ? 'like' : 'like-o'"
                          size="14"
                          :color="reply.liked ? '#FF6B6B' : '#999'"
                      />
                      <span class="action-count">{{ reply.likeCount || 0 }}</span>
                    </div>
                    <div class="action-item" @click="replyToComment(reply, comment)">
                      <van-icon name="reply" size="14" color="#999" />
                      <span>回复</span>
                    </div>
                  </div>

                  <!-- 子评论的回复输入框 -->
                  <div class="reply-input-container" v-if="reply.showReplyInput && admin">
                    <van-field
                        v-model="reply.replyText"
                        :placeholder="`回复 @${reply.username}`"
                        class="reply-field"
                        :border="false"
                        @keyup.enter="submitReply(reply)"
                    />
                    <div class="reply-input-actions">
                      <van-button
                          size="mini"
                          text
                          @click="cancelReply(reply)"
                      >
                        取消
                      </van-button>
                      <van-button
                          size="mini"
                          round
                          type="primary"
                          @click="submitReply(reply)"
                      >
                        回复
                      </van-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 主评论的回复输入框 -->
            <div class="reply-input-container" v-if="comment.showReplyInput && admin">
              <van-field
                  v-model="comment.replyText"
                  :placeholder="`回复 @${comment.username}`"
                  class="reply-field"
                  :border="false"
                  @keyup.enter="submitReply(comment)"
              />
              <div class="reply-input-actions">
                <van-button
                    size="mini"
                    text
                    @click="cancelReply(comment)"
                >
                  取消
                </van-button>
                <van-button
                    size="mini"
                    round
                    type="primary"
                    @click="submitReply(comment)"
                >
                  回复
                </van-button>
              </div>
            </div>
          </div>
        </div>

        <div class="no-comments" v-if="comments.length === 0">
          暂无评论，快来发表第一条评论吧~
        </div>
      </div>
    </div>

    <!-- 底部操作栏 -->
    <div class="bottom-action-bar">
      <div class="action-item">
        <van-icon name="star-o" size="22"  />
        <span class="action-text">{{ recipe.collectCount || 0 }}</span>
      </div>
      <div class="action-item">
        <van-icon name="comment-o" size="22" />
        <span class="action-text">{{ totalCommentCount }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import api from "@/api";

const route = useRoute()
const router = useRouter()

const admin = ref(JSON.parse(localStorage.getItem("admin")))

const recipe = ref({ user: {} })
const commentText = ref('')
const comments = ref([])
const targetType = ref(0)

// 计算总评论数
const totalCommentCount = computed(() => {
  const countComments = (list) => {
    let count = list.length
    list.forEach(c => {
      if (c.replyComments && c.replyComments.length) {
        count += countComments(c.replyComments)
      }
    })
    return count
  }
  return countComments(comments.value)
})

onMounted(() => {
  if (!admin.value) showToast('请先登录')
  getRecipe(route.query.id)
  getComments()
})

const getRecipe = (id) => {
  api.postReq("/recipe/getRecipeById?id=" + id).then(res => {
    if (res.data.code === 1) recipe.value = res.data.data
    else showToast(res.data.msg)
  }).catch(() => showToast('获取数据失败'))
}

const getComments = () => {
  const targetId = route.query.id
  api.postReq(`/comment1/getComment?targetType=${targetType.value}&targetId=${targetId}`)
      .then(res => {
        if (res.data.code === 1) {
          const process = (list) => list.map(c => ({
            ...c,
            liked: false,
            showReplyInput: false,
            replyText: '',
            replyComments: c.replyComments ? process(c.replyComments) : []
          }))
          comments.value = process(res.data.data)
        } else showToast(res.data.msg)
      }).catch(() => showToast('获取评论失败'))
}

// 提交顶级评论
const submitComment = () => {
  if (!admin.value) return showToast('请先登录')
  if (!commentText.value.trim()) return showToast('请输入评论内容')

  api.postReq("/comment1/addComment", {
    targetType: targetType.value,
    targetId: route.query.id,
    content: commentText.value,
    parentId: -1,
    userId: admin.value.id,
    username: admin.value.username,
    avatar: admin.value.avatar,
    isVip: admin.value.isVip
  }).then(res => {
    if (res.data.code === 1) {
      showToast('评论成功')
      commentText.value = ''
      getComments()
    } else showToast(res.data.msg)
  })
}

// 点赞
const likeComment = (item) => {
  if (!admin.value) return showToast('请先登录')

  const originalLiked = item.liked
  const originalCount = item.likeCount || 0

  item.liked = !item.liked
  item.likeCount = item.liked ? originalCount + 1 : originalCount - 1

  api.postReq("/comment1/like", { commentId: item.id, isLike: item.liked, userId: admin.value.id })
      .then(res => {
        if (res.data.code !== 1) {
          showToast(res.data.msg)
          item.liked = originalLiked
          item.likeCount = originalCount
        }
      }).catch(() => {
    showToast('操作失败')
    item.liked = originalLiked
    item.likeCount = originalCount
  })
}

// 点击“回复”
const replyToComment = (targetComment) => {
  if (!admin.value) return showToast('请先登录')

  const closeAll = (list) => list.forEach(c => {
    c.showReplyInput = false
    c.replyText = ''
    if (c.replyComments && c.replyComments.length) closeAll(c.replyComments)
  })
  closeAll(comments.value)

  targetComment.showReplyInput = true
  targetComment.replyText = ''
}

// 提交回复
const submitReply = (comment) => {
  if (!admin.value) return showToast('请先登录')
  if (!comment.replyText || !comment.replyText.trim()) return showToast('请输入回复内容')

  api.postReq("/comment1/addComment", {
    targetType: targetType.value,
    targetId: route.query.id,
    content: comment.replyText,
    parentId: comment.id,            // 直接回复的评论ID
    parentUsername: comment.username, // 显示对象用户名
    userId: admin.value.id,
    username: admin.value.username,
    avatar: admin.value.avatar,
    isVip: admin.value.isVip
  }).then(res => {
    if (res.data.code === 1) {
      showToast('回复成功')
      comment.replyText = ''
      comment.showReplyInput = false
      getComments()
    } else showToast(res.data.msg)
  }).catch(() => showToast('提交回复失败'))
}

const cancelReply = (comment) => {
  comment.replyText = ''
  comment.showReplyInput = false
}

const formatTime = (timeString) => {
  if (!timeString) return ''
  const date = new Date(timeString)
  const now = new Date()
  const diffMins = Math.floor((now - date) / 1000 / 60)
  const diffHours = Math.floor(diffMins / 60)
  const diffDays = Math.floor(diffHours / 24)
  const f = n => n < 10 ? '0' + n : n
  if (diffMins < 1) return '刚刚'
  else if (diffMins < 60) return `${diffMins}分钟前`
  else if (diffHours < 24) return `${diffHours}小时前`
  else if (diffDays < 30) return `${diffDays}天前`
  else return `${date.getFullYear()}-${f(date.getMonth()+1)}-${f(date.getDate())}`
}

const onClickLeft = () => router.back()
</script>



<style scoped>
/* 样式保持不变 */
.recipe-detail-page {
  background-color: #fff;
  min-height: 100vh;
  padding-bottom: 60px;
}

/* 导航栏样式 */
.transparent-nav {
  background-color: transparent;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
}

.van-nav-bar__left {
  color: #fff;
}

/* 主图样式 */
.recipe-main-image {
  width: 100%;
}

.main-img {
  width: 100%;
  height: 300px;
  object-fit: cover;
}

/* 标题和作者信息 */
.recipe-header {
  padding: 16px;
}

.recipe-title {
  font-size: 22px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  line-height: 1.3;
}

.author-info {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.author-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
}

.author-details {
  flex: 1;
}

.author-name {
  font-size: 15px;
  color: #333;
  display: flex;
  align-items: center;
  gap: 4px;
}

.publish-time {
  font-size: 12px;
  color: #999;
}

/* 菜品内容 */
.recipe-content {
  padding: 0 16px 16px;
}

.content-text {
  font-size: 15px;
  color: #333;
  line-height: 1.8;
}

.content-text img {
  width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 16px 0;
}

/* 通用章节样式 */
.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  padding-left: 4px;
  border-left: 3px solid #FF6B6B;
}

/* 评论区 */
.comments-section {
  padding: 16px;
  margin-top: 16px;
}

.comment-input {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 10px;
  background-color: #F9F9F9;
  border-radius: 20px;
}

.comment-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 10px;
}

.comment-field {
  flex: 1;
  background-color: transparent;
  font-size: 14px;
}

.submit-btn {
  margin-left: 10px;
  padding: 5px 15px;
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  display: flex;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #F5F5F5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-content {
  flex: 1;
}

.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.comment-author {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-right: 10px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  font-size: 14px;
  color: #333;
  line-height: 1.6;
  margin-bottom: 8px;
}

.comment-actions {
  display: flex;
  margin-bottom: 12px;
}

.action-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  font-size: 12px;
  color: #999;
  cursor: pointer;
  gap: 4px;
}

.action-count {
  color: #999;
}

/* 回复样式 */
.comment-replies {
  margin-left: 40px;
  margin-top: 10px;
}

.reply-item {
  display: flex;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #F9F9F9;
}

.reply-item:last-child {
  border-bottom: none;
}

.reply-avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 8px;
}

.reply-content {
  flex: 1;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.reply-author {
  font-size: 13px;
  font-weight: 500;
  color: #333;
  margin-right: 8px;
  display: flex;
  align-items: center;
  gap: 3px;
}

.reply-time {
  font-size: 11px;
  color: #999;
}

.reply-text {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 6px;
}

.reply-actions {
  display: flex;
}

/* 回复输入框 */
.reply-input-container {
  margin-left: 40px;
  margin-top: 10px;
  background-color: #F9F9F9;
  border-radius: 15px;
  padding: 8px 12px;
}

.reply-field {
  background-color: transparent;
  font-size: 13px;
  padding: 5px 0;
}

.reply-input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 5px;
}

.no-comments {
  text-align: center;
  padding: 30px 0;
  color: #999;
  font-size: 14px;
}

/* 底部操作栏 */
.bottom-action-bar {
  display: flex;
  align-items: center;
  padding: 8px 16px;
  background-color: #fff;
  border-top: 1px solid #F5F5F5;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
}

.bottom-action-bar .action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 20px;
  color: #666;
}

.bottom-action-bar .action-text {
  font-size: 12px;
  margin-top: 4px;
}
</style>